package com.example.sq.model.domain;

import com.example.sq.model.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Setter
public class AuthUser implements UserDetails {
    private static final long serialVersionUID = -206198483211133689L;
    private User user;
    private String userName;
    private Collection<? extends GrantedAuthority> authorities;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private boolean enabled;

    public AuthUser(){}

    public AuthUser(User user){
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        if (user == null){
            return authorities;
        }
        if (user.getRoles() != null && !user.getRoles().isEmpty()){
            user.getRoles().forEach(item -> {
                authorities.add(new SimpleGrantedAuthority(item.getRoleName()));
            });
        }
        if (user.getMenus() != null && !user.getMenus().isEmpty()) {
            user.getMenus().forEach(menu -> authorities.add(new
                    SimpleGrantedAuthority(menu.getUrl())));
        }

        return authorities;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return user!=null? user.getPassword():null;
    }

    @Override
    public String getUsername() {
        return user!=null?user.getUsername():null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return user!=null?user.getAccountNonExpired():null;
    }

    @Override
    public boolean isAccountNonLocked() {
        return user!=null?user.getAccountNonLocked():null;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return user!=null?user.getCredentialsNonExpired():null;
    }

    @Override
    public boolean isEnabled() {
        return user!=null?user.getEnabled():null;
    }

}


